package org.candan.spider.task.spider.ftp;
import java.io.IOException;  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
  
import org.apache.commons.logging.LogFactory;  
import org.apache.commons.net.ftp.FTP;  
import org.apache.commons.net.ftp.FTPClient;  
import org.apache.commons.net.ftp.FTPReply;  
public class FtpPool {

	 /** 
     * 在hiFrameworkConfig.properties配置文件中可设置ip、ftp的用户名、ftp的密码、root 
     */  
    private  String ip =""; //HiConfigHolder.getProperty("hi.upload.ftp.ip");  
    private  Integer port = 21;  
    private  String username ="anonymous"; // HiConfigHolder.getProperty("hi.upload.ftp.userName");  
    private  String pwd = "12@download"; //HiConfigHolder.getProperty("hi.upload.ftp.password");  
    private  String root = ""; //HiConfigHolder.getProperty("hi.upload.ftp.root");  
    private  Integer size = 0; //Integer.parseInt(HiConfigHolder.getProperty("hi.upload.ftp.clientSize"));  
      
    private  List<FTPClient> ftpLists = new ArrayList<FTPClient>();  
    private  HashMap<FTPClient, Integer> ftpStatus = new HashMap<FTPClient, Integer >();// 0表示可用 1 表示不可用   

    
    /**
     * @param ip
     * @param port
     * @param username
     * @param pwd
     * @param root 切换目录
     * @param size 连接池内链接个数
     */
    public FtpPool(String ip, Integer port, String username, String pwd,String root,Integer size){
    	this.ip = ip;
    	if(port != null )this.port= port;
    	if(username != null && !"".equals(username)) this.username = username;
    	if(pwd != null && !"".equals(pwd))this.pwd = pwd;
    	if(size != null  ) this.size = size;
    	if(root != null && !"".equals(root)) this.root = root;
    }
    /**
     * @param ip
     * @param username
     * @param pwd
     */
    public FtpPool(String ip, String username, String pwd){
    	this.ip = ip;
    	if(username != null && !"".equals(username)) this.username = username;
    	if(pwd != null && !"".equals(pwd))this.pwd = pwd;
    }
    /**
     * @param url eg.ftp://10.23.123.122/tobses
     */
    public FtpPool(String url){
    	String str = url.replace("ftp://", "");
    	this.ip = str.substring(0, str.indexOf("/"));
    	this.root = str.substring( str.indexOf("/"));
    } 
    
    /**
     * @param ip
     * @param root
     */
    public FtpPool(String ip, String root){
    	this.ip = ip;
    	if(root != null && !"".equals(root)) this.root = root;
    }
    /** 
    * @category:  连接服务器 
     */  
    public  void connect(FTPClient ftp) throws IOException {//必要时，可以设置编码为gbk   
        try {  
            ftp.connect(ip, port);  
            int reply = ftp.getReplyCode();//连接ftp后返回值类型   
            if(!FTPReply.isPositiveCompletion(reply)) {  
                ftp.disconnect();  
                System.exit(0);//throw new IOException("服务器拒绝连接.");   
            } else if(!ftp.login(username, pwd)) {  
                ftp.logout();  
                throw new IOException("FTP用户名或密码!");  
            }  
            ftp.setFileType(FTP.BINARY_FILE_TYPE);//使用二进制   
            if(root != null && !"".equals(root.trim())) {  
                ftp.changeWorkingDirectory(root);//改变目录路径   
            }  
        } catch(IOException ex) {  
            if(ftp.isConnected()) {  
                try {  
                    ftp.disconnect();  
                } catch(IOException ioex) {  
                    System.err.println("断开服务器连接失败");  
                }  
            }  
            System.err.println(ex.getMessage());  
        }  
    }  
  
    /** 
    * @category:  断开重新连接 
     */  
    public  void reConnect(FTPClient ftp) throws IOException {  
        try{  
            disConnect(ftp);  
        }catch(IOException e){}  
        connect(ftp);  
    }  
      
    /** 
    * @category:  断开连接 
     */  
    public  void disConnect(FTPClient ftp) throws IOException {  
        try {  
            ftp.noop(); // check that control connection is working OK   
            ftp.logout();  
        } catch(IOException ioe) {  
            System.err.println(ioe.getMessage());  
        } finally {  
            if(ftp.isConnected()) System.err.println("FTP未断开连接");  
        }  
    }  
      
    /** 
    * @category:  关闭ftp 
     */  
    public  void closeFtp(FTPClient ftp) throws IOException { 
        if(ftpLists.indexOf(ftp) < 0) {  
            disConnect(ftp);  
        } else {  
            ftpStatus.put(ftp, 0);  
        }
    }  
  
    /** 
    * @category:  获得一个ftp 
     */  
    public synchronized  FTPClient getFtpClient() throws IOException {  
        FTPClient ftp = null;  
        for(FTPClient client : ftpLists) {  
            //判断当前client是否已经有连接   
            if(ftpStatus.get(client) != null && ftpStatus.get(client).equals(new Integer(1))) {  
                ftpStatus.put(client, 1);  
                ftp = client;  
                break;  
            }  
        }  
        if(ftp == null) {
            //新建一个连接，放到ftpDownloads连接池   
            if(ftpLists.size() < size) {  
            	FTPClient newClient = new FTPClient();  
            	connect(newClient);  
                ftpLists.add(newClient);  
                ftpStatus.put(newClient, 1);  
                ftp = newClient;  
            }else{
              throw  new IOException("连接数已满！");
            }
        }  
        if(!ftp.isConnected()) {//判断ftp是否还保持连接状态   
            reConnect(ftp);  
        } else {  
            ftp.changeToParentDirectory();  
            if(root != null && !"".equals(root.trim())) ftp.changeWorkingDirectory(root);  
        }  
        return ftp;  
    }  
	/**
	 * @param args
	 * @throws IOException 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws IOException, InterruptedException {
		// TODO Auto-generated method stub
		FtpPool pool = new FtpPool("ftp://12.12.12.12/sdfsf");
		pool.getFtpClient();
		
		Thread.sleep(5000);
		pool.closeFtp(new FTPClient());
		
		System.out.println("12.12.1212/sdf".substring(0,"12.12.1212/sdf".indexOf("/")));
	}

}
